package me.wpf.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import me.wpf.utils.Contants;
import me.wpf.utils.ElasticSearchPoolConfig;
import me.wpf.utils.ElasticSearchPoolUtil;
import me.wpf.utils.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;


import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Description: es操作类
 *
 * @author 王朋飞
 * @create 2019/11/6
 */
public class Esdao {

    public static void main(String[] args) {
        createIndex();


    }

    /**
     * 判断索引是否存在
     *
     * @param index
     * @return
     */
    public static boolean inExistsIndex(String index) {
        boolean flag = false;
        RestHighLevelClient esClient = ElasticSearchPoolUtil.getEsClient();
        GetIndexRequest request = new GetIndexRequest(index);
        try {
            flag = esClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ElasticSearchPoolUtil.releaseClient(esClient);
        }
        return flag;
    }

    /**
     * 获取索引列表
     *
     * @return
     * @throws IOException
     */
    public static boolean getIndexList() {
        boolean flag = false;
        RestHighLevelClient esClient = ElasticSearchPoolUtil.getEsClient();
        try {


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ElasticSearchPoolUtil.releaseClient(esClient);
        }
        return flag;
    }

    public static boolean deleteIndex(List<String> indexs) {
        boolean flag = false;
        RestHighLevelClient esClient = ElasticSearchPoolUtil.getEsClient();
        try {
            for (String index : indexs) {
                DeleteIndexRequest request = new DeleteIndexRequest(index);
                AcknowledgedResponse delete = null;
                delete = esClient.indices().delete(request, RequestOptions.DEFAULT);
                flag = delete.isAcknowledged();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            ElasticSearchPoolUtil.releaseClient(esClient);
        }
        return flag;
    }

    /**
     * 创建索引
     *
     * @return
     */
    public static Boolean createIndex() {
        Boolean flag = false;
        RestHighLevelClient esClient = ElasticSearchPoolUtil.getEsClient();
        try {
            CreateIndexRequest request = new CreateIndexRequest(Contants.INDEX_NAME);
            request.settings(Settings.builder()
                    .put("index.number_of_shards", Contants.ES_MODEL.getNumberOfShards())
                    .put("index.number_of_replicas", Contants.ES_MODEL.getNumberOfReplicas())
            );
            CreateIndexResponse createIndexResponse = esClient.indices().create(request, RequestOptions.DEFAULT);
            flag = createIndexResponse.isAcknowledged();
        } catch (Exception e) {
        } finally {
            ElasticSearchPoolUtil.releaseClient(esClient);
        }
        return flag;
    }

//    /**
//     * 设置分片
//     *
//     * @param request
//     */
//    private void buildSetting(CreateIndexRequest request, String settings) {
//        request.settings(settings, XContentType.JSON);
//    }


    /**
     * 批量插入
     *
     * @param map
     */
    public static void insertBatch(Map<String, JSONObject> map) {
        RestHighLevelClient esClient = ElasticSearchPoolUtil.getEsClient();
        BulkRequest request = new BulkRequest();
        for (Map.Entry<String, JSONObject> entry : map.entrySet()) {
            request.add(new IndexRequest(Contants.INDEX_NAME).id(entry.getKey())
                    .source(JSON.toJSONString(entry.getValue()), XContentType.JSON));
        }
        try {
            BulkResponse bulk = esClient.bulk(request, RequestOptions.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            ElasticSearchPoolUtil.releaseClient(esClient);
        }
    }

    /**
     * 批量插入
     */
    public static boolean insertBatchV1(List<Map<String, Object>> list, RestHighLevelClient esClient) {
        boolean b = true;
//        RestHighLevelClient esClient = ElasticSearchPoolUtil.getEsClient();
        BulkRequest request = new BulkRequest();
        for (Map<String, Object> map : list) {
            request.add(new IndexRequest(Contants.INDEX_NAME)
                    .source(JSON.toJSONString(map), XContentType.JSON));
        }
        try {
            BulkResponse bulk = esClient.bulk(request, RequestOptions.DEFAULT);
            b = bulk.hasFailures();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //ElasticSearchPoolUtil.releaseClient(esClient);
        }
        return !b;
    }


    public static RestHighLevelClient getRestHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("10.2.145.224", 9200, "http")));
        return client;
    }

}
